<?php

class UserController extends Controller
{
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','login','logout','register','setdefaultlocal','forgetpassword'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('getuserbaseinfo','updatenickname','updateicon','updatepassword'),
                'users'=>array('@'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{

	}

	public function actionLogin()
	{
        Yii::trace($_COOKIE['PHPSESSID']);
		$model= new LoginForm();
		$model->username = $_POST['username'];
		$model->password = $_POST['password'];
		$result = $model->login();
        if ($result==true) {
           $user =  $_SESSION[_SESSIONID];
           $baseInfo = array();
           $baseInfo['nickname'] =$user['nickname'];
           $baseInfo['icon'] =$user['icon'];
           $baseInfo['logindays'] =$user['logindays'];
           $baseInfo['grade'] =$user['grade'];
           $baseInfo['session_id'] = session_id();
           $this->recordLog();
           Yii::trace(session_id());
           echoToMobile($baseInfo);
        } else {
            echoToError(_ERROR_USER_LOGIN_FAILUE);
        }
	}



    /**
     * 忘记密码
     * $email
     */
    public function actionForgetPassword($email) {
        echoToMobile('ok');
    }

	public function actionLogout()
	{
		Yii::app()->user->logout();
        echoToMobile('ok');
	}

    /**
     *  用户注册
     */
    public function actionRegister() {
        $user = new UserInfo();
        $user->username = $_POST['username'];
        $user->password = $_POST['password'];
        $user->nickname = $_POST['nickname'];
        $user->email = $_POST['email'];

        $user->email_validate = false;
        $user->logindays = 1;
        $user->grade = 0;
        $this->checkRegister($user->username,$user->nickname);
        $user->save(false);
        echoToMobile("ok");
    }


    /**
     * 设置默认的区域
     * @param string $local
     */
    public function actionSetDefaultLocal($local=_LOCAL_ZN) {
        $_SESSION[_LOCAL_FLAG] = $local;
        echoToMobile(session_id());
    }

    /**
     *
     */
    public function actionUpdatePassword() {

        $user = UserInfo::model()->findByPk(new MongoID(CommonUtils::getUserId()));
        if ($user->password!= $_POST['oldpass']) {
            echoToError(_ERROR_USER_LOGIN_FAILUE);
        }
        $user->password =  $_POST['newpass'];
        $user->update();
        echoToMobile('ok');
    }

    /**
     *
     */
    public function actionGetUserBaseInfo() {
        $user = UserInfo::model()->findByPk(new MongoID(CommonUtils::getUserId()));
        $result =  get_object_vars($user);
        unset($result['_id']);
        unset($result['password']);
        if(!empty($result['defaultAddress']))
        {
            $address = UserAddress::model()->findByPk(new MongoID($result['defaultAddress']));
            $result['defaultAddress'] = $address;
        }
        echoToMobile($result);
    }

    public function actionUpdateIcon(){
        $upload_handler = new UploadHandler(null,false);
        $uploadMessage = $upload_handler->post(false);
        $user = UserInfo::model()->findByPk(new MongoID(CommonUtils::getUserId()));
        $user->icon = $uploadMessage['files'][0]->url;
        $user->save();
        echoToMobile($user->icon);
    }

    /**
     * 更新用户昵称
     */
    public function actionUpdateNickname() {
        $user = UserInfo::model()->findByPk(new MongoID(CommonUtils::getUserId()));
        $result = $this->checkNickname($_POST['nickname'],CommonUtils::getUserId());
        if ($result) {
            $user->nickname = $_POST['nickname'];
            $user->update();
        }
        echoToMobile("ok");
    }

    private function recordLog() {
        $useraction = new UserActionlog();
        $useraction->userid = CommonUtils::getUserId();
        $useraction->event = _USER_ACTION_LOGIN;
        $useraction->createTime = time();
        $useraction->save();
    }

    private function checkRegister($username,$nickname) {
        $this->checkNickname($nickname);
        $this->checkUsername($username);
    }

    /**
     *
     */
    private function checkNickname($nickname,$uid=null) {
        $query = array(
            'conditions' => array(
                'nickname'=>array('=='=>$nickname),
            ),
        );
        $result = UserInfo::model()->find($query);
        if (!empty($result)) {
            if ($uid==null) {
                echoToError("昵称已存在");
            } else {
                if ($result->_id!=$uid) {
                    echoToError("昵称已存在");
                }
                return false;
            }
        }
        return true;
    }

    /**
     *
     */
    private function checkUsername($username,$uid=null) {
        $query = array(
            'conditions' => array(
                'username'=>array('=='=>$username),
            ),
        );
        $result = UserInfo::model()->find($query);
        if (!empty($result)) {
            if ($uid==null) {
                echoToError("用户名已存在");
            } else {
                if ($result->_id!=$uid) {
                    echoToError("用户名已存在");
                }
                return false;
            }
        }
        return true;
    }

}